using System;
using System.Web.Compilation;
using System.CodeDom;
using System.Web.UI;
using Microsoft.SharePoint;

namespace CKS.EBE
{
	[ExpressionEditor(typeof(ThemeExpressionEditor))]
	public class ThemeExpressionBuilder : ExpressionBuilder
	{
		public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
		{
			return ParseExpression(entry.Expression, entry.Type, context);
		}

		public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
		{
			return null;
		}

		public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
		{
			var rootWeb = SPContext.Current.Site.RootWeb;
			string serverRelativeURL = SPContext.Current.Web.ServerRelativeUrl;

			if (expression.ToLower().StartsWith("~theme/"))
			{
				string sRelativeUrl = BlogContext.Current.Settings.UseSiteCollectionThemes ? rootWeb.ServerRelativeUrl : serverRelativeURL;

				sRelativeUrl = sRelativeUrl.TrimEnd(new[] {'/'});
				return string.Format("{0}/Themes/{1}{2}", sRelativeUrl, BlogContext.Current.BlogTheme, expression.Substring(6));
			}

			if (expression.ToLower().StartsWith("~site"))
				return (serverRelativeURL + expression.Substring(5)).Replace("//", "/");

			if (expression.ToLower().StartsWith("~sitecollection"))
				return (rootWeb.ServerRelativeUrl + expression.Substring(5)).Replace("//", "/");

			return serverRelativeURL;
		}

		public override bool SupportsEvaluate
		{
			get
			{
				return true;
			}
		}
	}
}